/*
 * @Author: hutong huareu980@163.com
 * @Date: 2023-06-05 09:32:39
 * @LastEditors: hutong huareu980@163.com
 * @LastEditTime: 2023-06-09 11:00:04
 * @FilePath: /smart-web-admin/src/stores/userInfo.ts
 * @Description:
 */
import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { Session } from '/@/utils/storage';
import { useLoginApi } from '../api/login';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			userName: '',
			photo: '',
			time: 0,
			roles: [],
			authBtnList: [],
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			// if (Session.get('userInfo')) {
			// 	this.userInfos = Session.get('userInfo');
			// } else {
			const userInfos = <UserInfos>await this.getApiUserInfo();
			this.userInfos = userInfos;
			// }
		},
		// 模拟接口数据
		// https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
		async getApiUserInfo() {
			try {
				const userId = Cookies.get('userId');
				const { result } = await useLoginApi().userInfo(userId);
				const defaultRoles = ['admin'];
				const defaultAuthBtnList = ['btn.add', 'btn.del', 'btn.edit', 'btn.link'];
				const userInfos = {
					userName: result.username,
					photo:
						result.username === 'admin'
							? 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500'
							: 'https://img2.baidu.com/it/u=2370931438,70387529&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
					time: new Date().getTime(),
					roles: defaultRoles,
					authBtnList: defaultAuthBtnList,
				};
				Session.set('userInfo', userInfos);
				return userInfos;
				// resolve(userInfos);
			} catch (error) {}
		},
	},
});
